package com.europe.business.europebusiness.ui.activity;

import android.content.Intent;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.europe.business.europebusiness.R;
import com.europe.business.europebusiness.ui.activity.base.ActionBarActivity;
import com.europe.business.europebusiness.ui.bean.CompanyBean1;
import com.europe.business.europebusiness.ui.bean.CompanyCategoryBean;
import com.europe.business.europebusiness.ui.bean.CompanySearchBean;
import com.europe.business.europebusiness.ui.bean.ICommonList;
import com.europe.business.europebusiness.ui.bean.ImproveEourpeBean;
import com.europe.business.europebusiness.ui.bean.JsonBean;
import com.europe.business.europebusiness.ui.bean.Sector1Bean;
import com.europe.business.europebusiness.ui.bean.Sector2Bean;
import com.europe.business.europebusiness.ui.bean.User;
import com.europe.business.europebusiness.ui.bean.UserLogin;
import com.europe.business.europebusiness.ui.common.Commons;
import com.europe.business.europebusiness.ui.net.ICompany;
import com.europe.business.europebusiness.ui.net.IUser;
import com.europe.business.europebusiness.ui.utils.NetUtils;
import com.europe.business.europebusiness.ui.utils.SpUtils;
import com.europe.business.europebusiness.ui.utils.Utils;
import com.europe.business.europebusiness.ui.view.CircleView;
import com.wildma.pictureselector.PictureSelector;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

import static com.europe.business.europebusiness.ui.common.Commons.SERVER_URL;
import static com.europe.business.europebusiness.ui.utils.Utils.getSystemLanguage;
import static com.wildma.pictureselector.PictureSelector.PICTURE_PATH;

public class InfoCompanyActivity extends ActionBarActivity implements CompoundButton.OnCheckedChangeListener, View.OnClickListener {

    private static final String TAG = "InfoCompanyActivity";
    private CheckBox exportCb;
    private CheckBox importCb;
    private CheckBox willCb;
    private LinearLayout isWillLin;
    private TextView companyName;
    private LinearLayout companySort;
    private LinearLayout companyMainBusiness;
    private LinearLayout companyCountry;
    private LinearLayout companyCity;
    private LinearLayout companySector1;
    private LinearLayout companySector2;
    private EditText companyAddress;
    private TextView companySortTv;
    private TextView companyMainBusinessTv;
    private TextView companyCityTv;
    private TextView companyCountryTv;
    private TextView companySector1Tv;
    private TextView companySector2Tv;
    private EditText companyAddressEt;
    private CircleView logo;
    private static final int REQUEST_CODE_NAME = 999;
    private static final int REQUEST_CODE_SORT = 1000;
    private static final int REQUEST_CODE_CITY = 1001;
    private static final int REQUEST_CODE_COUNTRY = 10001;
    private static final int REQUEST_CODE_SECTOR1 = 1002;
    private static final int REQUEST_CODE_SECTOR2 = 1003;
    private static final int REQUEST_CODE_MAINBUSINESS = 1004;
    private String sector1dataId;
    private String sector2dataId;
    private String countryId;
    private String cityId;
    private TextView infoToMain;
    private String logoPath;
    private String accountId;
    private LinearLayout companyCbLin;
    private String companyId;
    private int mCompanySort;
    private String username;
    private String password;

    @Override
    protected int setMainContent() {
        return R.layout.activity_info_company;
    }

    @Override
    protected void initView() {
        super.initView();
        setToolbarNavigationIcon(R.drawable.back);
        setActionRight(false, "",null);
        setTitle(getString(R.string.title_reg_info));

        exportCb = findViewById(R.id.export_cb);
        importCb = findViewById(R.id.import_cb);
        willCb = findViewById(R.id.will_cb);

        exportCb.setOnCheckedChangeListener(this);
        importCb.setOnCheckedChangeListener(this);
        willCb.setOnCheckedChangeListener(this);

        isWillLin = findViewById(R.id.is_will);
        companySector1 = findViewById(R.id.company_sector1);
        companySector2 = findViewById(R.id.company_sector2);
        companySector1Tv=findViewById(R.id.company_sector1_tv);
        companySector2Tv=findViewById(R.id.company_sector2_tv);
        companyName = findViewById(R.id.company_name_et);
        companyAddress = findViewById(R.id.company_address_et);
        companySort = findViewById(R.id.company_sort);
        companyMainBusiness = findViewById(R.id.company_mainbusiness);
        companyCity = findViewById(R.id.company_city);
        companyCountry = findViewById(R.id.company_country);
        companySortTv = findViewById(R.id.company_sort_tv);
        companyMainBusinessTv = findViewById(R.id.company_mainbusiness_tv);
        companyCityTv = findViewById(R.id.company_city_tv);
        infoToMain = findViewById(R.id.info_to_main);
        companyAddressEt = findViewById(R.id.company_address_et);
        companyCbLin = findViewById(R.id.company_cb);
        companySort.setOnClickListener(this);
        companyMainBusiness.setOnClickListener(this);
        companyCity.setOnClickListener(this);
        companyName.setOnClickListener(this);
        companySector1.setOnClickListener(this);
        companySector2.setOnClickListener(this);
        logo = findViewById(R.id.logo);
        logo.setOnClickListener(this);
        companyCity.setOnClickListener(this);
        companyCountry.setOnClickListener(this);
        infoToMain.setOnClickListener(this);
        accountId = getIntent().getStringExtra("accountId");
        username = getIntent().getStringExtra("username");
        password = getIntent().getStringExtra("password");
        mCompanySort = getIntent().getIntExtra("sort", -1);
        if(mCompanySort == SelectIdentityActivity.SORT_CHINA || mCompanySort == SelectIdentityActivity.SORT_EUROPE_CHINA){
            companyCbLin.setVisibility(View.GONE);
        }
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        switch (buttonView.getId()) {
            case R.id.export_cb://

                break;
            case R.id.import_cb:

                break;
            case R.id.will_cb:
                if (isChecked) {
                    isWillLin.setVisibility(View.VISIBLE);
                } else {
                    isWillLin.setVisibility(View.GONE);
                }
                break;

        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.company_sort:
                Intent intent = new Intent(this, CompanySortActivity.class);
                startActivityForResult(intent, REQUEST_CODE_SORT);
                break;
            case R.id.company_sector1:
                Intent intentSection1 = new Intent(this, Sector1Activity.class);
                startActivityForResult(intentSection1, REQUEST_CODE_SECTOR1);
                break;
            case R.id.company_sector2:
                if(TextUtils.isEmpty(sector1dataId)){
                    showToastLong(getString(R.string.info_select_sector_please));
                    return;
                }
                Intent intentSection2 = new Intent(this, Sector2Activity.class);
                intentSection2.putExtra("sector1dataId", sector1dataId);
                startActivityForResult(intentSection2, REQUEST_CODE_SECTOR2);
                break;
            case R.id.company_mainbusiness:
                if(TextUtils.isEmpty(sector1dataId)){
                    showToastLong(getString(R.string.info_select_sector_please));
                    return;
                }
                if(TextUtils.isEmpty(sector2dataId)){
                    showToastLong(getString(R.string.info_select_sector2_please));
                    return;
                }
                Intent intentMain = new Intent(this, Sector2Activity.class);
                intentMain.putExtra("sector1dataId", sector1dataId);
                intentMain.putExtra("sector2dataId", sector2dataId);
                startActivityForResult(intentMain, REQUEST_CODE_MAINBUSINESS);
                break;
            case R.id.company_city:
                if(TextUtils.isEmpty(countryId)){
                    showToastLong(getString(R.string.info_select_country_please));
                    return;
                }
                Intent intent1 = new Intent(this, CityActivity.class);
                intent1.putExtra("countryId", Integer.parseInt(countryId));
                startActivityForResult(intent1, REQUEST_CODE_CITY);
                break;
            case R.id.logo:
                /**
                 * create()方法参数一是上下文，在activity中传activity.this，在fragment中传fragment.this。参数二为请求码，用于结果回调onActivityResult中判断
                 * selectPicture()方法参数分别为 是否裁剪、裁剪后图片的宽(单位px)、裁剪后图片的高、宽比例、高比例。都不传则默认为裁剪，宽200，高200，宽高比例为1：1。
                 */
                PictureSelector
                        .create(InfoCompanyActivity.this, PictureSelector.SELECT_REQUEST_CODE)
                        .selectPicture(true, 200, 200, 1, 1);
                break;
            case R.id.company_name_et:
                Intent intet = new Intent(this, SearchActivity1.class);
                startActivityForResult(intet, REQUEST_CODE_NAME);
                break;
            case R.id.company_country:

                Intent intentCountry = new Intent(this, CountryActivity.class);

                startActivityForResult(intentCountry, REQUEST_CODE_COUNTRY);
                break;
            case R.id.info_to_main:
                String companyN = companyName.getText().toString();
                String comcompanySortpanyN = companySortTv.getText().toString();
                String companySector1 = companySector1Tv.getText().toString();
                String companySector2 = companySector2Tv.getText().toString();
                String companyMainBusiness = companyMainBusinessTv.getText().toString();
                String companyCountry = companyCountryTv.getText().toString();
                String companyCity = companyCityTv.getText().toString();
                String companyAddress = companyAddressEt.getText().toString();

                if(TextUtils.isEmpty(companyN) || TextUtils.isEmpty(comcompanySortpanyN) || TextUtils.isEmpty(companySector1)
                        || TextUtils.isEmpty(companySector2) || TextUtils.isEmpty(companyMainBusiness) || TextUtils.isEmpty(companyCountry)
                        || TextUtils.isEmpty(companyAddress)){
                    showToastShort(getString(R.string.info_input_info_please));
                    return;
                }
                ImproveEourpeBean bean  = new ImproveEourpeBean();
                if(!TextUtils.isEmpty(companyId)){
                    bean.setId(companyId);
                }
                bean.setName(companyN);
                bean.setAccountVoId(accountId);
                bean.setSector1(companySector1);
                bean.setSector2(companySector2);
                bean.setCompanyCategory(comcompanySortpanyN);
                bean.setAddress(companyAddress);
                bean.setCountry(companyCountry);
                bean.setCity(companyCity);
                bean.setMainBusiness(companyMainBusiness);
                if(!TextUtils.isEmpty(logoPath)){
                    bean.setLogo(logoPath);
                }
                bean.setLanguage(Utils.getSystemLanguage(InfoCompanyActivity.this));
                Map<String, Object> map = new HashMap<String, Object>();
                try {
                    map = Utils.objectToMap(bean);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                showProgressDialog();
                if(mCompanySort == SelectIdentityActivity.SORT_CHINA || mCompanySort == SelectIdentityActivity.SORT_EUROPE_CHINA){
                    Retrofit retrofit = NetUtils.getRetrofit();
                    ICompany company = retrofit.create(ICompany.class);
                    Call<JsonBean> call = company.improveCompanyInformation(map);
                    call.enqueue(new Callback<JsonBean>() {
                        @Override
                        public void onResponse(Call<JsonBean> call, Response<JsonBean> response) {
                            dismissProgressDialog();
                            JsonBean bean = response.body();
                            if(null != bean){
                                if(bean.getErrorCode() == 1){
                                    login(username, password);
                                }else{
                                    showToastShort(bean.getErrorMessage());
                                }
                            }else{
                                showToastShort(getString(R.string.info_request_err));
                            }


                        }

                        @Override
                        public void onFailure(Call<JsonBean> call, Throwable t) {
                            dismissProgressDialog();
                            Log.e(TAG, t.getMessage());
                            showToastShort(getString(R.string.info_request_err));
                        }
                    });
                }else{
                    Retrofit retrofit = NetUtils.getRetrofit();
                    ICompany company = retrofit.create(ICompany.class);
                    Call<JsonBean> call = company.improveEuropeCompany(map);
                    call.enqueue(new Callback<JsonBean>() {
                        @Override
                        public void onResponse(Call<JsonBean> call, Response<JsonBean> response) {
                            dismissProgressDialog();
                            JsonBean bean = response.body();
                            if(null != bean){
                                if(bean.getErrorCode() == 1){
                                    startAct(MainActivity.class);
                                }else{
                                    showToastShort(bean.getErrorMessage());
                                }
                            }else{
                                showToastShort(getString(R.string.info_request_err));
                            }


                        }

                        @Override
                        public void onFailure(Call<JsonBean> call, Throwable t) {
                            dismissProgressDialog();
                            Log.e(TAG, t.getMessage());
                            showToastShort(getString(R.string.info_request_err));
                        }
                    });
                }


                break;


        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == RESULT_CANCELED){
            return;
        }
        /*结果回调*/
        if (requestCode == PictureSelector.SELECT_REQUEST_CODE) {
            if (data != null) {
                String picturePath = data.getStringExtra(PictureSelector.PICTURE_PATH);

                //上传图片,返回图片url地址
                showProgressDialog();
                File file = new File(picturePath);
                String fileName = file.getName();
                RequestBody requestFile = RequestBody.create(MediaType.parse("image/jpeg"), file);
                /**
                 *file部分，最终拼接成以下部分（注意“logo”是后台定义好的，后台会用它作为key去查询你传的图片信息）：
                 *Content-Disposition: form-data; name="logo"; filename=xxxxx
                 *Content-Type: image/jpeg
                 *Content-Length: 52251(图片流字节数组的长度，底层的Okhttp帮我们计算了)
                 *...(文件流)
                 */
                MultipartBody.Part body = MultipartBody.Part.createFormData("logo", fileName, requestFile);
                Retrofit retrofit = new Retrofit.Builder()
                        .addConverterFactory(GsonConverterFactory.create())
                        .baseUrl(Commons.SERVER_URL)
                        .build();
                IUser user = retrofit.create(IUser.class);
                Call<JsonBean> call = user.uploadLogo(body, Utils.getSystemLanguage(this));
                call.enqueue(new Callback<JsonBean>() {
                    @Override
                    public void onResponse(Call<JsonBean> call, Response<JsonBean> response) {
                        dismissProgressDialog();
                        JsonBean bean = response.body();
                        if(bean != null){
                            if(bean.getErrorCode() == 1){
                                String urlPath = bean.getData();
                                logoPath = urlPath;
//                            Commons.SERVER_URL + "app/user/" +urlPath
                                String path = Commons.SERVER_URL +urlPath;
                                Glide.with(InfoCompanyActivity.this).load(path).into(logo);
                                if(urlPath != null){
                                    logo.setBackgroundResource(R.color.bg_color);
                                }
                                showToastLong(getString(R.string.upload_success));
                            }else{
                                showToastLong(getString(R.string.upload_failed));
                            }

                        }else{
                            showToastLong(getString(R.string.upload_failed));
                        }
                    }

                    @Override
                    public void onFailure(Call<JsonBean> call, Throwable t) {
                        Log.e(TAG, t.getMessage());
                        dismissProgressDialog();
                        showToastLong(getString(R.string.upload_failed));
                    }
                });


                // 加载本地图片
//                File file1 = new File(picturePath);
//                Glide.with(this).load(file1).into(logo);
            }
        }else if(requestCode == REQUEST_CODE_SORT){
            if(data != null){
                CompanyCategoryBean.Data data1 = (CompanyCategoryBean.Data) data.getSerializableExtra("data");
                companySortTv.setText(data1.getCategory());
                String id = data1.getItemId();

            }
        }else if(requestCode == REQUEST_CODE_NAME){
            if(data != null){
                String name = "";
                try {
                    CompanySearchBean.CompanySearch category = (CompanySearchBean.CompanySearch) data.getSerializableExtra("data");
                    name = category.getName();
                    companyId = category.getId();
                    getCompanyInfo(companyId);
                }catch (ClassCastException e){
                    name = data.getStringExtra("data");
//                    initViewValue(null);

                }
                companyName.setText(name);
            }

        }else if(requestCode == REQUEST_CODE_CITY){
            if(data != null){
                ICommonList commonData = (ICommonList)data.getSerializableExtra("data");
                companyCityTv.setText(commonData.getItemContent());
                cityId = commonData.getItemId();
            }
        }else if(requestCode == REQUEST_CODE_SECTOR1){
            if(data != null){
                Sector1Bean.Data sector1data = (Sector1Bean.Data) data.getSerializableExtra("data");
                companySector1Tv.setText(sector1data.getSector1name());
                sector1dataId = sector1data.getSector1id();
                sector2dataId = "";
                companySector2Tv.setText("");
                companyMainBusinessTv.setText("");
            }

        }else if(requestCode == REQUEST_CODE_SECTOR2){
            if(data != null){
                Sector2Bean.Data sector2data = (Sector2Bean.Data) data.getSerializableExtra("data");
                companySector2Tv.setText(sector2data.getSector2name());
                sector2dataId = sector2data.getSector2id();
                companyMainBusinessTv.setText("");
            }
        }else if(requestCode == REQUEST_CODE_COUNTRY){
            if(data != null){
                ICommonList sector2data = (ICommonList)data.getSerializableExtra("data");
                companyCountryTv.setText(sector2data.getItemContent());
                countryId = sector2data.getItemId();
                cityId = "";
                companyCityTv.setText("");
            }
        }else if(requestCode == REQUEST_CODE_MAINBUSINESS){
            if(data != null){
                ICommonList commonData = (ICommonList)data.getSerializableExtra("data");
                companyMainBusinessTv.setText(commonData.getItemContent());
            }
        }
    }

    private void getCompanyInfo(String companyId){
        showProgressDialog();
        Retrofit retrofit = NetUtils.getRetrofit();
        ICompany companyApi = retrofit.create(ICompany.class);
        Call<CompanyBean1> call = companyApi.companyInfoNotToken(companyId, Utils.getSystemLanguage(InfoCompanyActivity.this));
        call.enqueue(new Callback<CompanyBean1>() {
            @Override
            public void onResponse(Call<CompanyBean1> call, Response<CompanyBean1> response) {
                dismissProgressDialog();
                CompanyBean1 bean1 = response.body();
                if(bean1 != null){
                    CompanyBean1.CompanyData data = bean1.getData();
                    if(data != null){
                        initViewValue(data);
                    }else{
                        showToastShort(bean1.getErrorMessage());
                    }

                }else{
                    showToastShort(getString(R.string.info_request_err));
                }

            }

            @Override
            public void onFailure(Call<CompanyBean1> call, Throwable t) {
                Log.e(TAG, t.getMessage());
                dismissProgressDialog();
                showToastShort(getString(R.string.info_request_err));
            }
        });
    }

    private void initViewValue(CompanyBean1.CompanyData data){
        if(data == null){
            companySortTv.setText("");
            companySector1Tv.setText("");
            companySector2Tv.setText("");
            companyMainBusinessTv.setText("");
            companyCountryTv.setText("");
            companyCityTv.setText("");
            companyAddressEt.setText("");

            //setViewOK(true);//设置控件不可编辑

        }else{
//            companyName.setText(data.getName());
            String path = data.getLogo();
            Glide.with(InfoCompanyActivity.this).load(path).into(logo);
            companySortTv.setText(data.getCompanyCategory());
            companySector1Tv.setText(data.getSector1());
            companySector2Tv.setText(data.getSector2());
            companyMainBusinessTv.setText(data.getMainBusiness());
            companyCountryTv.setText(data.getCountry());
            companyCityTv.setText(data.getCity());
            companyAddressEt.setText(data.getAddress());

            //setViewOK(false);//设置控件不可编辑
        }

    }

    private void setViewOK(boolean isOK){
        //        companyName.setEnabled(false);
        companySortTv.setClickable(isOK);
        companySector1Tv.setClickable(isOK);
        companySector2Tv.setClickable(isOK);
        companyMainBusinessTv.setClickable(isOK);
        companyCountryTv.setClickable(isOK);
        companyCityTv.setClickable(isOK);
        companyAddressEt.setEnabled(isOK);
    }

    private void login(String name, String pw){
        if(TextUtils.isEmpty(name) || TextUtils.isEmpty(pw)){
            showToastLong(getString(R.string.info_check_param_err));
            return;
        }
        showProgressDialog(getString(R.string.info_logining));
        Retrofit retrofit = new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl(Commons.SERVER_URL)
                .build();
        IUser user = retrofit.create(IUser.class);
        User u = new User();
        u.setName(name);
        u.setPassword(pw);
        Call<UserLogin> call =  user.login(name, pw, Utils.getSystemLanguage(this));
        call.enqueue(new Callback<UserLogin>() {
            @Override
            public void onResponse(Call<UserLogin> call, Response<UserLogin> response) {
                dismissProgressDialog();
                if(null != response){
                    UserLogin userLogin = response.body();
                    if(userLogin != null){
                        if(userLogin.getErrorCode() == 1){
                            SpUtils.saveToSp(InfoCompanyActivity.this, "token", userLogin.getData().getToken());
                            startAct(MainActivity.class);
                            finish();
                        }else{
                            //showToastLong(getString(R.string.login_failure));
                            showToastLong(userLogin.getErrorMessage());
                        }
                        Log.i("Login", response.body()+"");
                    }else{
                        showToastLong(getString(R.string.login_failure));
                    }
                }else{
                    showToastLong(getString(R.string.login_failure));
                }
            }

            @Override
            public void onFailure(Call<UserLogin> call, Throwable t) {
                dismissProgressDialog();
                Log.i("Login_err", "失败"+t.getMessage());
                showToastLong(getString(R.string.login_failure));
            }
        });
    }
}